from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from .models import *


# 关注序列化
class userxu(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


# 关注的人
class gaunzhu(APIView):
    def post(self, request):
        name = request.data.get('name')
        print(name)
        user_obj = User.objects.filter(idol__fans__name__contains=name)
        ser = userxu(user_obj, many=True)
        return Response(ser.data)


# 查看粉丝
class fensi(APIView):
    def post(self, request):
        name = request.data.get('name')
        print(name)
        user_obj = User.objects.filter(fans__idos__name__contains=name)
        ser = userxu(user_obj, many=True)
        return Response(ser.data)


# 评论序列化
class pinglunmodelxu(serializers.ModelSerializer):
    class Meta:
        model = pinglunmodel
        fields = '__all__'


# 无限极树型函数
def pinglun(data):
    shuju = []
    tree = {}
    ping_id = ''
    for i in data:
        item = i
        tree[item['id']] = item
    root = None
    for i in data:
        obj = i
        if not obj['pid']:
            root = tree[obj['id']]
            shuju.append(root)
        else:
            pin_id = obj['pid']
            if 'childlist' not in tree[pin_id]:
                tree[pin_id]['childlist'] = []
            tree[pin_id]['childlist'].append(tree[obj['id']])
    return shuju


# 调用函数评论view
class pinglunview(APIView):
    def get(self, request):
        suoyou = pinglunmodel.objects.all()
        ser = pinglunmodelxu(suoyou, many=True)
        pinglist = pinglun(ser)
        return Response(pinglist)


# 筛选序列化
class yonghushaixuanxu(serializers.ModelSerializer):
    class Meta:
        model = yonghushaixuan
        fields = '__all__'


# 筛选价格案列
class shaiview(APIView):
    def post(self, request):
        payment = request.data.get('payment')
        payment1 = request.data.get('payment1')
        if all([payment, payment1]):
            cha = yonghushaixuan.objects.filter(age__gt=payment, age__lte=payment1)
            ser = yonghushaixuanxu(cha, many=True)
            return Response(ser.data)
        elif payment:
            cha = yonghushaixuan.objects.filter(age__lte=payment)
            ser = yonghushaixuanxu(cha, many=True)
            return Response(ser.data)
        elif payment1:
            cha = yonghushaixuan.objects.filter(age__gte=payment1)
            ser = yonghushaixuanxu(cha, many=True)
            return Response(ser.data)
        else:
            cha = yonghushaixuan.objects.all()
            ser = yonghushaixuanxu(cha, many=True)
            return Response(ser.data)


import qrcode
import io
from PIL import Image


# 生成邀请码
class yanzheng_code(APIView):
    def get(self, request):
        username = request.GET.get('username')
        user_obj = yanzhengmamodel.objects.filter(username=username).first()
        qr = qrcode.QRCode(
            version=4,  # 生成二维码尺寸的大小 1-40 1:21*21（21+(n-1)*4）
            error_correction=qrcode.constants.ERROR_CORRECT_M,  # L:7% M:15% Q:25% H:30%
            box_size=10,  # 每个格子的像素大小
            border=2,  # 边框的格子宽度大小
        )
        # save_path = 'theqrcode.png'  # 生成后的保存文件
        # logo = 'logo.jpg'  # logo图片
        qr.add_data(username)
        qr.make(fit=True)
        img = qr.make_image()
        buf = io.BytesIO()
        img.save(buf, 'png')
        return Response({'msg': '牛逼'})


# 链式过滤

def index(request):
    _fields = ['payment__gte', 'payment__lte', 'age__gte', 'age__lte', 'city__contains']
    if request.method == 'GET':
        payment = range(0, 30000, 20000)
        return render(request, 'index.html', locals())

    if request.method == 'POST':
        filter = {f: request.POST[f] for f in request.POST if f in _fields}
        print(filter)
        data = yonghushaixuan.objects.filter(**filter)
        return render(request, 'result.html', locals())
